// 加载统计数据
async function loadStatisticsData() {
    try {
        // 获取统计数据
        const statsResponse = await fetch(`${API_BASE_URL}/statistics`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (!statsResponse.ok) {
            throw new Error(`HTTP error! status: ${statsResponse.status}`);
        }
        
        const stats = await statsResponse.json();
        
        // 获取所有订单和配送员数据用于图表
        const ordersResponse = await fetch(`${API_BASE_URL}/orders`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        const deliveryPersonsResponse = await fetch(`${API_BASE_URL}/delivery-persons`, {
            method: 'GET',
            credentials: 'same-origin'
        });
        
        if (ordersResponse.ok && deliveryPersonsResponse.ok) {
            const orders = await ordersResponse.json();
            const deliveryPersons = await deliveryPersonsResponse.json();
            
            // 显示统计图表
            displayStatisticsCharts(orders, deliveryPersons);
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
        showAlert('加载统计数据失败，请刷新页面重试。', 'danger');
    }
}

// 显示统计图表
function displayStatisticsCharts(orders, deliveryPersons) {
    // 订单状态分布
    displayOrderStatusChart(orders);
    
    // 配送员状态分布
    displayDeliveryPersonStatusChart(deliveryPersons);
}

// 显示订单状态分布图表
function displayOrderStatusChart(orders) {
    const orderStatusChart = document.getElementById('orderStatusChart');
    if (!orderStatusChart) return;
    
    // 统计各状态订单数量
    const statusCounts = {};
    orders.forEach(order => {
        if (!statusCounts[order.status]) {
            statusCounts[order.status] = 0;
        }
        statusCounts[order.status]++;
    });
    
    // 准备图表数据
    const labels = [];
    const data = [];
    const backgroundColors = [];
    
    for (const status in statusCounts) {
        labels.push(formatOrderStatus(status));
        data.push(statusCounts[status]);
        backgroundColors.push(getChartColor(status));
    }
    
    // 创建简单的图表显示
    orderStatusChart.innerHTML = '';
    
    if (labels.length === 0) {
        orderStatusChart.innerHTML = '<div class="text-center py-5">暂无订单数据</div>';
        return;
    }
    
    // 创建简单的条形图
    const maxValue = Math.max(...data);
    const chartHtml = labels.map((label, index) => {
        const percentage = (data[index] / maxValue) * 100;
        return `
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <span>${label}</span>
                    <span>${data[index]}个</span>
                </div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${percentage}%; background-color: ${backgroundColors[index]}" 
                        aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
        `;
    }).join('');
    
    orderStatusChart.innerHTML = chartHtml;
}

// 显示配送员状态分布图表
function displayDeliveryPersonStatusChart(deliveryPersons) {
    const deliveryPersonStatusChart = document.getElementById('deliveryPersonStatusChart');
    if (!deliveryPersonStatusChart) return;
    
    // 统计各状态配送员数量
    const statusCounts = {};
    deliveryPersons.forEach(person => {
        if (!statusCounts[person.status]) {
            statusCounts[person.status] = 0;
        }
        statusCounts[person.status]++;
    });
    
    // 准备图表数据
    const labels = [];
    const data = [];
    const backgroundColors = [];
    
    for (const status in statusCounts) {
        labels.push(formatDeliveryPersonStatus(status));
        data.push(statusCounts[status]);
        backgroundColors.push(getChartColor(status, true));
    }
    
    // 创建简单的图表显示
    deliveryPersonStatusChart.innerHTML = '';
    
    if (labels.length === 0) {
        deliveryPersonStatusChart.innerHTML = '<div class="text-center py-5">暂无配送员数据</div>';
        return;
    }
    
    // 创建简单的条形图
    const maxValue = Math.max(...data);
    const chartHtml = labels.map((label, index) => {
        const percentage = (data[index] / maxValue) * 100;
        return `
            <div class="mb-3">
                <div class="d-flex justify-content-between mb-1">
                    <span>${label}</span>
                    <span>${data[index]}人</span>
                </div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${percentage}%; background-color: ${backgroundColors[index]}" 
                        aria-valuenow="${percentage}" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
            </div>
        `;
    }).join('');
    
    deliveryPersonStatusChart.innerHTML = chartHtml;
}

// 获取图表颜色
function getChartColor(status, isDeliveryPerson = false) {
    if (isDeliveryPerson) {
        switch (status) {
            case 'IDLE': return '#28a745'; // 绿色
            case 'DELIVERING': return '#007bff'; // 蓝色
            case 'BUSY': return '#ffc107'; // 黄色
            case 'OFFLINE': return '#6c757d'; // 灰色
            default: return '#6c757d';
        }
    } else {
        switch (status) {
            case 'PENDING_PAYMENT': return '#6c757d'; // 灰色
            case 'PENDING_COLLECTION': return '#17a2b8'; // 青色
            case 'COLLECTED': return '#007bff'; // 蓝色
            case 'TRANSPORTING': return '#007bff'; // 蓝色
            case 'OUT_FOR_DELIVERY': return '#ffc107'; // 黄色
            case 'DELIVERY_FAILED': return '#dc3545'; // 红色
            case 'SIGNED': return '#28a745'; // 绿色
            case 'COMPLETED': return '#28a745'; // 绿色
            case 'CANCELLED': return '#dc3545'; // 红色
            default: return '#6c757d';
        }
    }
}

// 导出函数
window.loadStatisticsData = loadStatisticsData;